package com.dingniu8;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ifeng.stock.ResultTable;

class Parser {

	/**
	 * convert a valid html-table to ResultTable
	 * 
	 * @param pageline the html table is saved in one String
	 * @return
	 */
	static ResultTable parse(String pageline) {
		boolean isStock;
		Pattern p;

		if (pageline.matches(Constants.stock_table)) {
			p = Pattern.compile(Constants.stock_pattern);
			isStock = true;
		} else if (pageline.matches(Constants.block_table)) {
			p = Pattern.compile(Constants.block_pattern);
			isStock = false;
		} else {
			// skip trash lines
			return null;
		}

		// if a valid table is found, split it into NUM_TABLE_CELL stocks or
		// blocks
		Matcher m = p.matcher(pageline);
		ResultTable r = new ResultTable(Constants.NUM_TABLE_CELL);

		int i;
		for (i = 0; i < Constants.NUM_TABLE_CELL; i++) {
			if (m.find()) { //find next cell
				String cell = m.group(); //System.out.println(cell);

				//get the code
				String tmp;
				int beginIndex, endIndex;
				if (isStock) {
					tmp = Constants.stock_code_prefix;
				} else {
					tmp = Constants.block_code_prefix;
				}
				beginIndex = cell.indexOf(tmp) + tmp.length();
				r.table[i].setCode( Integer.parseInt(cell.substring(beginIndex, beginIndex+6)) );
				
				//get the name
				beginIndex = cell.indexOf(Constants.name_prefix) + Constants.name_prefix.length();
				endIndex = cell.indexOf(Constants.name_suffix);
				r.table[i].setName ( cell.substring(beginIndex, endIndex));
				//System.out.println(r.table[i].getCode());
			}
		}

		if (i != Constants.NUM_TABLE_CELL) {
			System.out.println("Warning: parse cells failed.");
			return null;
		}
		else{
			return r;
		}
	}

}
